<template>
  <div class="flexContent">
    <h3>采购信息</h3>
    <el-form ref="ruleForm" :model="form" :rules="rules" label-width="auto" label-position="left" class="demo-ruleForm">
      <el-row>
        <el-col :span="8" :offset="0">
          <el-form-item label="供应商" prop="supplierId">
            <el-select v-model="form.supplierId" placeholder="请选择供应商"
              :disabled="formData.tableData.length != 0 || isDetail || Boolean(id)" style="width: 80%;" filterable
              popper-class="eloption">
              <el-option v-for="item in supplierList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item prop="desireDate" label="期望到货日期">
            <el-date-picker v-model="form.desireDate" :disabled="isDetail" type="date" placeholder="选择期望到货日期"
              :clearable="false" :picker-options="pickerOptions" value-format="yyyy-MM-dd" style="width: 80%;" />
          </el-form-item>

        </el-col>
        <el-col :span="8" :offset="0">
          <el-form-item label="收货仓库" prop="warehouseId">
            <el-select v-model="form.warehouseId" placeholder="请选择收货仓库"
              :disabled="formData.tableData.length != 0 || isDetail || Boolean(id)" style="width: 80%;" filterable
              popper-class="eloption">
              <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item prop="expireDate" label="订单失效日期">
            <el-date-picker v-model="form.expireDate" :disabled="isDetail || !isAdmin" type="date"
              placeholder="选择订单失效日期" :clearable="false" :picker-options="pickerOptions" value-format="yyyy-MM-dd"
              style="width: 80%;" />
          </el-form-item>

        </el-col>
        <el-col :span="8" :offset="0">
          <el-form-item label="采购员" prop="userName">
            <el-input v-clearEmoji v-model.trim="form.userName" disabled clearable style="width: 80%;" />
          </el-form-item>
          <el-form-item label="备注" prop="remake">
            <el-input v-clearEmoji v-model.trim="form.remake" maxlength="100" show-word-limit :disabled="isDetail"
              placeholder="请输入备注信息" style="width: 80%;" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div>
      <el-button v-if="!isDetail" class="addBtn" :disabled="isDetail" @click="submitForm('ruleForm')">添加商品</el-button>
      <el-button v-if="!Boolean(id)" class="addBtn" :disabled="isDetail" @click="selTempOrder()">调暂存单</el-button>
    </div>
    <div class="table">
      <el-form ref="formData" :model="formData" @submit.native.prevent>
        <el-table border class="tablebox" :data="formData.tableData" :max-height="!isDetail ? '500' : '550'"
          show-summary :summary-method="getSummaries" style="width: 100%" size="medium">
          <el-table-column align="center" type="index" label="序号" width="80" />
          <el-table-column align="center" prop="name" label="商品名称"
            :min-width="elTableAdaptationWidth('name', formData.tableData)" />
          <!-- <el-table-column align="center" prop="mnemonic" label="助记符"
            :min-width="elTableAdaptationWidth('mnemonic', formData.tableData)" /> -->
          <el-table-column align="center" prop="firstCode" label="商品条码"
            :min-width="elTableAdaptationWidth('firstCode', formData.tableData)" />
          <el-table-column align="center" prop="standard" label="规格"
            :min-width="elTableAdaptationWidth('standard', formData.tableData)" />
          <el-table-column align="center" prop="unitName" label="单位" width="70" />
          <el-table-column align="center" prop="producer" label="产地"
            :min-width="elTableAdaptationWidth('producer', formData.tableData)" />
          <el-table-column align="center" prop="buyNumber" label="采购数量" min-width="120">
            <template slot-scope="scope">
              <el-form-item v-if="!isDetail" :prop="'tableData.' + scope.$index + '.buyNumber'"
                :rules="tableRules(formData.tableData[scope.$index])">
                <el-input v-clearEmoji v-model.trim.number="scope.row.buyNumber" :disabled="isDetail" require
                  placeholder="请输入数量" class="group-inp" size="small" />
              </el-form-item>
              <span v-else>{{ scope.row.buyNumber }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="bigPacking" label="大包装" min-width="80" />
          <el-table-column align="center" prop="pieceNumber" label="件数" min-width="70" />
          <el-table-column align="center" prop="agreedPrice" label="协议进价（元）" min-width="130" />
          <el-table-column align="center" prop="buyMoney" label="进货金额（元）" min-width="130" />
          <el-table-column align="center" prop="stock" label="现有库存" min-width="100" v-if="!isDetail" />
          <el-table-column align="center" prop="rotationDays" label="回转天数" min-width="100" v-if="!isDetail" />
          <el-table-column align="center" prop="grossRate" label="毛利率" width="100" />
          <el-table-column align="center" prop="taxRate" label="税率" min-width="60" />
          <el-table-column align="center" label="操作" v-if="!isDetail" fixed="right" width="100">
            <template slot-scope="{row}">
              <el-button type="text" style="color: red;" @click="delSelectById(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <div class="returnBtn">
      <el-button class="celBtn" @click="cancleAddGoods">返 回</el-button>
      <el-button v-if="!isDetail" class="addBtn" @click="submitData('formData')">确 定</el-button>
      <el-button v-if="!Boolean(id)" class="addBtn" @click="tempSave('formData')">暂 存</el-button>
    </div>
    <el-dialog destroy-on-close title="添加商品" :visible.sync="goodsAddDialog" width="60%" :close-on-click-modal="false">
      <div class="dinner">
        <div class="left">
          <div class="tp">
            <div style="margin-bottom: 10px;">
              <el-input v-clearEmoji v-model.trim="search.name" placeholder="助记符/名称/条码" clearable
                style="width: 40%;margin-right: 20px;" @keyup.enter.native="searchGoodsTableList" />
              <el-cascader ref="cascaderRef" v-model="search.categoryId" filterable clearable placeholder="请选择商品分类"
                :options="options" style="width: 40%;margin-right: 20px;"
                :props="{ value: 'id', label: 'name', checkStrictly: true, emitPath: false }"
                @change="categoryChange" />
              <el-button @click="searchGoodsTableList">筛选</el-button>
            </div>
            <el-table border ref="multipleTable" :data="goodsTableData" max-height="337" style="width: 100%"
              size="medium" :row-class-name="tableRowClassName" :row-key="getRowKeys"
              :header-cell-class-name="cellClass" @selection-change="handleSelectionChanges" @row-click="handlerClick">
              <el-table-column align="center" type="selection" width="55" :selectable="selectable" />
              <el-table-column align="center" prop="name" label="商品名称"
                :min-width="elTableAdaptationWidth('name', goodsTableData)" />
              <el-table-column align="center" prop="firstCode" label="商品条码"
                :min-width="elTableAdaptationWidth('firstCode', goodsTableData)" />
              <el-table-column align="center" prop="mnemonic" label="助记符"
                :min-width="elTableAdaptationWidth('mnemonic', goodsTableData)" />
              <!-- <el-table-column align="center" prop="producer" label="产地" /> -->
            </el-table>
          </div>
          <div>
            <el-pagination background :current-page.sync="pageT.pageNum" :page-sizes="$pageSizes"
              :page-size.sync="pageT.pageSize" layout="total, ->,prev, pager, next, sizes" :total="pageT.total"
              @size-change="changeGoodsPageSize" @current-change="getGoodsTableList" />
          </div>
        </div>
        <div ref="rightBox" class="right">
          <div class="title">
            已选商品
          </div>
          <div class="list">
            <div v-for="o in selectList" :key="o.commodityId" class="item">
              <p>{{ o.name }}</p>
              <i class="el-icon-close" style="font-size: 24px;" @click="delSelection(o.commodityId)" />
            </div>
          </div>

        </div>
      </div>
      <div slot="footer">
        <el-button class="addBtn" style="width:120px" @click="addSelectGoods">添加选中商品</el-button>
        <el-button class="addBtn" @click="submitOrder">确 定</el-button>
        <el-button class="celBtn" @click="cancleDialog">取 消</el-button>
      </div>
    </el-dialog>




    <el-dialog title="调暂存单" :visible.sync="tempTableVisible" width="80%">
      <el-table border :data="gridData" ref="tempTable" row-key="id" class="tablebox" height="500px"
        @row-click="handlerTempClick" size="medium">
        <el-table-column label="序号" width="80" align="center">
          <template scope="scope">
            <el-radio v-model="radio" class="radio" :label="scope.$index"><span @click.native.stop>{{ scope.$index + 1
                }}</span></el-radio>
          </template>
        </el-table-column>
        <el-table-column property="supplierName" align="center" label="供应商名称" />
        <el-table-column property="warehouseName" align="center" label="收货仓库" />
        <el-table-column property="userName" align="center" label="暂存人" />
        <el-table-column property="createTime" align="center" label="暂存时间">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime | parseTime }}</span>
          </template>
        </el-table-column>
        <el-table-column property="createTime" align="center" label="操作">
          <template v-slot="{ row }">
            <div>
              <el-button type="text" style="margin-right: 10px; color: red" @click="$delFn('暂存单', delTempSave, row)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="paginationBox">
        <el-pagination :current-page="page.pageNum" background :page-sizes="$pageSizes" :page-size="page.pageSize"
          layout="total,->, sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
          @current-change="getTempOrder" />
      </div>
      <div slot="footer">
        <el-button class="celBtn" @click="cancelFn">取消</el-button>
        <el-button class="addBtn" @click="confirmFn">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { DecimalUtils } from '@/utils/math'
import { cloneDeep } from 'lodash'
import { parseTime4 } from '@/utils'
import { mapState } from 'vuex'
import { reqGoodsList, reqSupplierList, reqWarehouseList, reqAddProcureOrder, reqOrderDetailsById, reqUpdateBuyOrder, reqTempSaveOrder, reqTempSaveList, reqTempSaveDetail, reqDelTempSaveOrder } from '@/api/procure'
import { reqGoodsCategory } from '@/api/warehouse'
import dayjs from 'dayjs'
import { isAdmin } from '@/api/user';
import { getDictValueSource } from '@/api/dictionary'
export default {
  name: 'ProcureOrderAdd',

  data() {
    return {
      pickerOptions: {
        disabledDate(time) {
          const today = new Date();
          today.setHours(0, 0, 0, 0); // 设置为今天的凌晨
          return time.getTime() <= today.getTime() - 1;
        }
      },
      // 供应商列表
      supplierList: [],
      // 仓库列表
      warehouseList: [],
      // 添加之前的表单
      form: {
        userName: '',
        supplierId: '',
        desireDate: '',
        expireDate: '',
        remake: '',
        warehouseId: ''
      },
      rules: {
        userName: [
          { required: true, message: '请输入采购员姓名', trigger: 'blur' },
        ],
        supplierId: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ],
        warehouseId: [
          { required: true, message: '请选择收货仓库', trigger: 'change' }
        ],
        expireDate: [
          { required: true, message: '请选择期望到货时间', trigger: 'change' }
        ],
        remake: [
          { max: 100, message: '请勿超过100个字符', trigger: 'blur' }
        ]
      },
      // 表格
      formData: {
        tableData: []
      },
      // 搜索
      search: {
        name: '',
        categoryId: '',
        level: 1
      },
      isSearch: false,
      // 级联选择器配置项
      options: [],
      // 弹窗内的表格数据
      goodsTableData: [],
      pageT: {
        pageNum: 1,
        pageSize: 20,
        total: 0
      },
      // 选中的商品数量
      selectList: [],
      // 控制弹窗
      goodsAddDialog: false,
      // 弹窗的表格选中绑定的数组
      multipleSelection: [],
      // 订单总金额
      totalPrice: 0,
      // 订单总数量
      totalNum: 0,
      // 件数总量
      totalPiece: 0,
      // 判断是否是管理员
      isAdmin: false,
      invalidDay: 5,
      // 暂存单
      tempTableVisible: false,
      gridData: [],
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tempId: '',
      radio: 0,
    }
  },
  computed: {
    ...mapState({
      userName: state => state.user.userInfo.sysUser.employeeName,
      userId: state => state.user.userInfo.sysUser.id
    }),
    id() {
      return this.$route.query.id
    },
    isDetail() {
      return this.$route.query.isDetail == '1'
    },
    warehouseId() {
      return this.$route.query.warehouseId
    },
    isEdit() {
      if (this.$route.query.id && this.$route.query.isDetail == '2') {
        return true
      } else return false
    }
  },
  async created() {
    this.form.userName = this.userName
    this.form.expireDate = parseTime4(dayjs().add(this.invalidDay, 'day'))
    this.form.desireDate = parseTime4(new Date())
    this.getSupplierList();
    this.getWarehouseList();
    this.getDictValueSource();
    this.getIsAdmin();
    if (this.id) {
      this.getOrderDetailsById()
    }
  },
  methods: {
    // 获取订单失效日期
    async getDictValueSource() {
      let res = await getDictValueSource("BUY_ORDER_CONFIG");
      if (res.code === 200) {
        this.invalidDay = res.data.INVALID_DAY;
      }
    },
    // 是否是管理员
    async getIsAdmin() {
      const res = await isAdmin();
      if (res.code === 200) {
        console.log(res, "成功");
        this.isAdmin = res.data;
      }
      console.log(res);
    },
    // 表单验证
    tableRules(row, scope) {
      // console.log(scope);
      return [
        { required: true, message: '不能为空' },
        { type: 'number', message: '必须为数字值' },
        {
          pattern: /^\+?[1-9]\d*$/,
          message: "必须为正整数",
          trigger: "blur",
        },
        {
          validator: (rule, value, callback) => {
            if (value % row.bigPacking != 0) {
              callback("须为大包装的倍数")
            } else if (value == 0) {
              callback("须为正整数");
            } else {
              callback();
            }
          }
        }
      ]
    },
    // 筛选
    async getGoodsTableList() {
      const { warehouseId, supplierId } = this.form
      const { pageNum, pageSize } = this.pageT
      if (!this.isSearch) {
        this.search.name = undefined;
        this.search.categoryId = undefined;
        this.search.level = undefined;
      }
      const { name, categoryId, level } = this.search
      const resObj = { warehouseId, supplierId, name, categoryId, categoryLevel: level, pageNum, pageSize }
      const res = await reqGoodsList(resObj)
      if (res.code === 200) {
        this.goodsTableData = res.data.list
        this.pageT.total = res.data.total
      }
    },
    // 采购订单搜索
    searchGoodsTableList() {
      this.pageT.pageNum = 1;
      this.pageT.pageSize = 20;
      this.isSearch = true;
      this.getGoodsTableList();
    },
    // 获取供应商列表
    async getSupplierList() {
      const res = await reqSupplierList()
      if (res.code === 200) {
        this.supplierList = res.data.list
      }
    },
    // 获取仓库列表
    async getWarehouseList() {
      const res = await reqWarehouseList()
      if (res.code === 200) {
        this.warehouseList = res.data
      }
    },
    // 获取订单详情回显
    async getOrderDetailsById() {
      const res = await reqOrderDetailsById({ id: this.id, warehouseId: this.warehouseId })
      if (res.code === 200) {
        const { data } = res
        // 回显form
        this.form = {
          userName: data.username,
          supplierId: data.supplierId,
          desireDate: data.desireDate,
          expireDate: data.expireDate,
          remake: data.remake,
          warehouseId: data.warehouseId
        }
        this.totalNum = data.totalNum
        this.totalPrice = data.totalPrice
        this.totalPiece = data.totalPiece

        // 回显表格
        this.formData = {
          tableData: data.detailsList
        }
      }
    },
    // 获取总计
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        // console.log(data);
        data.forEach(item => {
          if (!isNaN(item.buyNumber)) {
            // item.buyMoney = item.buyNumber * item.agreedPrice;
            // item.buyMoney = (item.buyNumber * item.agreedPrice).toFixed(2);
            item.buyMoney = DecimalUtils.multiply(Number(item.buyNumber), Number(item.agreedPrice))
            // console.log(item.buyMoney,"@@@@@@");
            if (DecimalUtils.divide(Number(item.buyNumber), Number(item.bigPacking)) % 1 == 0) {
              item.pieceNumber = DecimalUtils.divide(Number(item.buyNumber), Number(item.bigPacking))
            } else {
              item.pieceNumber = DecimalUtils.divide(Number(item.buyNumber), Number(item.bigPacking)).toFixed(2)
            }
          } else {
            item.pieceNumber = 0
            item.buyMoney = 0
          }
        })
        const values = data.map(item => Number(item[column.property]))
        if (column.property === 'buyNumber' || column.property === 'buyMoney' || column.property === 'pieceNumber') {
          if (this.isDetail) {
            // 详情状态用后台数据回显
            if (column.property === 'buyNumber') {
              sums[index] = this.totalNum
            } else if (column.property === 'buyMoney') {
              sums[index] = this.totalPrice
            } else {
              sums[index] = this.totalPiece
            }
          } else {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return DecimalUtils.add(prev, value)
              } else {
                return prev
              }
            }, 0)

            if (column.property === 'buyNumber') {
              this.totalNum = sums[index]
            } else if (column.property === 'buyMoney') {
              this.totalPrice = sums[index]
            } else {
              this.totalPiece = sums[index]
            }
          }
        }
      })
      return sums
    },
    // 确定按钮
    submitData(formName) {
      // ruleForm
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.$refs[formName].validate(async (valid1) => {
            if (valid1) {
              if (this.formData.tableData.length === 0) {
                this.$message.warning("请添加采购商品");
                return;
              }
              const data = this.formData.tableData
              console.log(data);
              const { totalNum, totalPrice, userId, totalPiece, tempId } = this
              // let { supplierId, warehouseId, remake, expireDate, desireDate } = this.form;
              const buyDetailsList = data.map(item => {
                return {
                  commodityId: item.commodityId,
                  buyMoney: item.buyMoney,
                  buyNumber: item.buyNumber,
                  pieceNumber: item.pieceNumber,
                }
              })
              const reqObj = { totalNum, totalPrice, userId, ...this.form, buyDetailsList, totalPiece, tempId }
              let res = {}
              console.log(reqObj, "采购订单请求数据");
              if (!this.isEdit) {
                res = await reqAddProcureOrder(reqObj)
              } else {
                res = await reqUpdateBuyOrder({ ...reqObj, id: this.id })
              }

              if (res.code === 200) {
                if (this.isEdit) {
                  this.$message.success('订单修改成功')
                } else {
                  this.$message.success('订单创建成功')
                }
                this.closeTag()
              } else {
                // this.$message.error(res.message)
              }
            } else {
              this.$message.warning('请输入合法的数据')
            }
          })
        } else {
          this.$message.warning('请检查输入信息');
        }
      })
    },
    tempSave(formName) {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.$refs[formName].validate(async (valid1) => {
            if (valid1) {
              if (this.formData.tableData.length === 0) {
                this.$message.warning("请添加采购商品");
                return;
              }
              const data = this.formData.tableData
              console.log(data);
              const { totalNum, totalPrice, userId, totalPiece, tempId } = this
              // let { supplierId, warehouseId, remake, expireDate, desireDate } = this.form;
              const buyDetailsList = data.map(item => {
                return {
                  commodityId: item.commodityId,
                  buyMoney: item.buyMoney,
                  buyNumber: item.buyNumber,
                  pieceNumber: item.pieceNumber,
                }
              })
              const reqObj = { totalNum, totalPrice, userId, ...this.form, buyDetailsList, totalPiece, tempId }
              let res = await reqTempSaveOrder(reqObj)
              if (res.code === 200) {
                this.$message.success('订单暂存成功')
                this.closeTag()
              }
            } else {
              this.$message.warning('请输入合法的数据')
            }
          })
        } else {
          this.$message.warning('请检查输入信息')
        }
      })
    },
    // 添加商品按钮
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.goodsAddDialog = true
          this.pageT.pageNum = 1
          this.search = { name: '', categoryId: '', level: 1 }
          this.getGoodsTableList()
          this.getGoodsCategory()
          this.selectList = cloneDeep(this.formData.tableData)
          this.multipleSelection = []
        } else {
          this.$message.warning('请选择供应商和收货仓库')
          return false
        }
      })
    },
    // 调暂存单
    selTempOrder() {
      this.tempTableVisible = true;
      this.getTempOrder();
    },
    async delTempSave(row) {
      let res = await reqDelTempSaveOrder({ id: row.id });
      if (res.code === 200) {
        // 判断当前数据是不是当页最后一条，如果是页码减1
        this.$message.success('删除成功');
        if (this.gridData.length === 1 && this.page.pageNum > 1)
          this.page.pageNum--;
        this.getTempOrder();
      } else {
        // this.$message.error(res.message);
      }
    },
    async getTempOrder() {
      this.radio = 0;
      let res = await reqTempSaveList({ pageNum: this.page.pageNum, pageSize: this.page.pageSize });
      if (res.code === 200) {
        this.gridData = res.data.list
        this.page.total = res.data.total;
      }
    },
    handlerTempClick(row) {
      this.radio = this.gridData.indexOf(row);
    },
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;
      this.gridData = []
      this.getTempOrder();
    },
    async confirmFn() {
      let index = this.radio;
      if (this.gridData.length <= 0) {
        this.$message.warning('请先选择暂存单');
        return;
      }
      const id = this.gridData[index]?.id;
      let res = await reqTempSaveDetail({ id });
      if (res.code === 200) {
        let warehouseId = res.data.warehouseId;
        let supplierId = res.data.supplierId;
        let warehouseBool = this.warehouseList.some(item => item.id === warehouseId);
        let supplierBool = this.supplierList.some(item => item.id === supplierId)
        if (warehouseBool && supplierBool) {
          this.tempId = id;
          this.form = {
            warehouseId,
            supplierId,
            remake: res.data.remake,
            expireDate: parseTime4(dayjs().add(this.invalidDay, 'day')),
            desireDate: parseTime4(new Date()),
            userName: this.userName
          }
          this.formData.tableData = res.data.detailsList;
          this.tempTableVisible = false;
        } else {
          if (!warehouseBool && !supplierBool) {
            this.$message.warning('所选暂存单未找到匹配的收货仓库和供应商');
            return;
          } else if (!warehouseBool) {
            this.$message.warning('所选暂存单未找到匹配的收货仓库');
            return;
          } else {
            this.$message.warning('所选暂存单未找到匹配的供应商');
            return;
          }
        }
      }
    },
    cancelFn() {
      this.gridData = [];
      this.page = {
        total: 0,
        pageNum: 1,
        pageSize: 10
      }
      this.tempTableVisible = false;
      this.radio = 0;
    },
    async getGoodsCategory() {
      const res = await reqGoodsCategory()
      if (res.code === 200) {
        this.options = res.data
      }
    },
    // 返回上一页
    cancleAddGoods() {
      this.closeTag()
    },
    categoryChange(e) {
      const nodes = this.$refs.cascaderRef.getCheckedNodes()
      this.search.level = nodes[0]?.level
    },

    // 全选按钮禁用
    cellClass(row) {
      if (this.disableSelection) {
        if (row.columnIndex === 0) {
          return 'disableSelection'
        }
      }
    },
    handlerClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row);
    },
    // 选中事件
    handleSelectionChanges(val) {
      this.multipleSelection = val
    },
    // 弹窗表格的键
    getRowKeys(row) {
      return row.commodityId
    },
    // 选中列样式
    tableRowClassName({ row, rowIndex }) {
      for (let i = 0; i < this.selectList.length; i++) {
        const item = this.selectList[i]
        if (item.commodityId === row.commodityId) {
          return 'warning-row'
        }
      }
      return ''
    },
    // 复选框禁用
    selectable(row, rowIndex) {
      for (let i = 0; i < this.selectList.length; i++) {
        const item = this.selectList[i]
        if (item.commodityId === row.commodityId) {
          // this.$refs.multipleTable.toggleRowSelection(row, true)
          return false
        }
      }
      return true
    },
    changeGoodsPageSize() {
      this.pageT.pageNum = 1
      this.getGoodsTableList()
    },
    // 删除选中
    delSelection(commodityId) {
      this.selectList = this.selectList.filter(item => {
        if (item.commodityId !== commodityId) {
          return true
        } else {
          let index = this.goodsTableData.findIndex(it => it.commodityId === commodityId)
          // 不能用上面的item，因为指向的不是一个地址，所以要用表格中的数据
          this.$refs.multipleTable.toggleRowSelection(this.goodsTableData[index], false)
          return false
        }
      })
      this.multipleSelection = [...this.multipleSelection, ...this.selectList];
    },
    // 添加选中商品
    addSelectGoods() {
      this.multipleSelection.forEach((litem) => {
        if (!this.selectList.find(obj => obj.commodityId === litem.commodityId)) {
          this.selectList.push({
            ...litem,
            pieceNumber: 0
          })
        }
      })
      console.log(this.selectList, "@@@");
      this.$nextTick(() => {
        this.$refs.rightBox.scrollTo(0, this.$refs.rightBox.scrollHeight)
      })
    },
    // 提交表单
    submitOrder() {
      // multipleSelection
      // 是否进行提示
      let flag = false;
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach(item => {
          console.log(this.selectList.findIndex(it => it.commodityId == item.commodityId));
          if (this.selectList.findIndex(it => it.commodityId == item.commodityId) == -1) {
            flag = true;
            return;
          }
        })
      }
      if (flag) {
        this.$alert("有未添加的选中商品，是否继续提交？", '提示', {
          type: 'warning',
          confirmButtonText: '确认提交',
          cancelButtonText: '继续添加',
          showCancelButton: true,
        }).then(() => {
          this.formData.tableData = Object.assign([], this.selectList)
          this.goodsAddDialog = false
        }).catch(() => {

        })
      } else {
        this.formData.tableData = Object.assign([], this.selectList)
        this.goodsAddDialog = false
      }
      // this.formData.tableData = Object.assign([], this.selectList)
      // this.goodsAddDialog = false
    },
    // 删除已选商品
    delSelectById(row) {
      let index = this.formData.tableData.findIndex(item => item.commodityId === row.commodityId);
      this.formData.tableData.splice(index, 1);
    },
    cancleDialog() {
      this.goodsAddDialog = false
      this.selectList = [];
      this.multipleSelection = [];
      this.goodsTableData = [];
    }
  }
}
</script>
<style lang="scss" scoped>
.el-table .warning-row {
  background: #f5f7fa;
  color: #ccc;
}

.el-table .disableSelection .cell .el-checkbox__inner {
  display: none;
  position: relative;
}

.el-table .disableSelection .cell::before {
  content: '';
  position: absolute;
}
</style>

<style lang="scss" scoped>
.flexContent {
  h3 {
    margin: 0;
    margin-bottom: 10px;
  }
}

.dinner {
  display: flex;

  .left {
    margin-right: 20px;
    width: 500px;
    border: 1px solid #a9a9a9;
    border-radius: 4px;
    padding: 10px;
    min-height: 400px;
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  .el-cascader {
    .el-input {
      width: 100%
    }
  }

  .right {
    width: 250px;
    height: 450px;
    overflow-y: auto;
    border: 1px solid #a9a9a9;
    border-radius: 4px;
    padding: 10px;

    /* 定义滚动条的样式 */
    &::-webkit-scrollbar {
      width: 8px;
      /* 滚动条宽度 */
    }

    /* 定义滚动条轨道的样式 */
    &::-webkit-scrollbar-track {
      background: #f1f1f1;
      /* 轨道背景颜色 */
    }

    /* 定义滚动条滑块的样式 */
    &::-webkit-scrollbar-thumb {
      background: #b6b6b6;
      /* 滑块颜色 */
    }

    /* 定义滚动条滑块悬停时的样式 */
    &::-webkit-scrollbar-thumb:hover {
      background: #a0a0a0;
      /* 滑块悬停时的颜色 */
    }

    .title {
      padding: 10px 0;
      margin-bottom: 10px;
      font-size: 18px;
      font-weight: bold;
      border-bottom: 1px solid #ccc;
    }

    .list {
      font-size: 16px;

      .item {
        display: flex;
        justify-content: space-between;
        padding: 10px 0;
        align-items: center;

        p {
          margin: 0;
        }

        i {
          cursor: pointer;
        }
      }
    }
  }
}
</style>
